var CT = require('./modules/country-list');
var AM = require('./modules/account-manager');
var EM = require('./modules/email-dispatcher');
var EXM = require('./modules/excel-manager');
var IFM = require('./modules/information-manager');
var FIM = require('./modules/file-manager');
var REM = require('./modules/reservation-manager'); //管理预约
var WRM = require('./modules/weather-manager'); //管理天气


//哈希函数
var crypto = require('crypto');
var moment = require('moment');

module.exports = function (app) {

    // main login page //
    app.get('/', function (req, res) {
        // check if the user's credentials are saved in a cookie //
        if (req.cookies.user == undefined || req.cookies.pass == undefined) {
            res.render('login', {title: 'Hello - Please Login To Your Account'});
        } else {
            // attempt automatic login //
            AM.autoLogin(req.cookies.user, req.cookies.pass, function (o) {
                if (o != null) {
                    req.session.user = o;
                    res.redirect('/home');
                } else {
                    res.render('login', {title: 'Hello - Please Login To Your Account'});
                }
            });
        }
    });

    app.post('/', function (req, res) {
        AM.manualLogin(req.body['user'], req.body['pass'], function (e, o) {
            if (!o) {
                res.status(400).send(e);
            } else {
                req.session.user = o;
                if (req.body['remember-me'] == 'true') {
                    res.cookie('user', o.user, {maxAge: 900000});
                    res.cookie('pass', o.pass, {maxAge: 900000});
                }
                res.status(200).send(o);
            }
        });
    });

    // creating new accounts //
    app.get('/signup', function (req, res) {
        res.render('signup', {title: 'Signup', countries: CT});
    });

    app.post('/signup', function (req, res) {
        AM.addNewAccount({
            name: req.body['name'],
            email: req.body['email'],
            user: req.body['user'],
            pass: req.body['pass'],
            country: req.body['country']
        }, function (e) {
            if (e) {
                res.status(400).send(e);
            } else {
                res.status(200).send('ok');
            }
        });
    });

    // password reset //
    app.post('/lost-password', function (req, res) {
        // look up the user's account via their email //
        AM.getAccountByEmail(req.body['email'], function (o) {
            if (o) {
                EM.dispatchResetPasswordLink(o, function (e, m) {
                    // this callback takes a moment to return //
                    // TODO add an ajax loader to give user feedback //
                    if (!e) {
                        res.status(200).send('ok');
                    } else {
                        for (k in e) console.log('ERROR : ', k, e[k]);
                        res.status(400).send('unable to dispatch password reset');
                    }
                });
                0
            } else {
                res.status(400).send('email-not-found');
            }
        });
    });


    app.get('/reset-password', function (req, res) {
        var email = req.query["e"];
        var passH = req.query["p"];
        AM.validateResetLink(email, passH, function (e) {
            if (e != 'ok') {
                res.redirect('/');
            } else {
                // save the user's email in a session instead of sending to the client //
                req.session.reset = {email: email, passHash: passH};
                res.render('reset', {title: 'Reset Password'});
            }
        })
    });

    app.post('/reset-password', function (req, res) {
        var nPass = req.body['pass'];
        // retrieve the user's email from the session to lookup their account and reset password //
        var email = req.session.reset.email;
        // destory the session immediately after retrieving the stored email //
        req.session.destroy();
        AM.updatePassword(email, nPass, function (e, o) {
            if (o) {
                res.status(200).send('ok');
            } else {
                res.status(400).send('unable to update password');
            }
        })
    });

    //Guard unLogin User
    app.all('*', function (req, res, next) {
        if (req.session.user == null) {
            // if user is not logged-in redirect back to login page //
            res.redirect('/');
        } else {
            next();
        }
    });

    app.get('/home', function (req, res) {
        res.render('home', {
            title: 'Control Panel',
            udata: req.session.user
        });
    });

    app.get('/account', function (req, res) {
        res.render('account', {
            title: 'Control Panel',
            countries: CT,
            udata: req.session.user
        });
    });

    app.post('/account', function (req, res) {
        AM.updateAccount({
            id: req.session.user._id,
            name: req.body['name'],
            email: req.body['email'],
            pass: req.body['pass'],
            country: req.body['country']
        }, function (e, o) {
            if (e) {
                res.status(400).send('error-updating-account');
            } else {
                req.session.user = o;
                // update the user's login cookies if they exists //
                if (req.cookies.user != undefined && req.cookies.pass != undefined) {
                    res.cookie('user', o.user, {maxAge: 900000});
                    res.cookie('pass', o.pass, {maxAge: 900000});
                }
                res.status(200).send('ok');
            }
        });
    });

    app.post('/logout', function (req, res) {
        res.clearCookie('user');
        res.clearCookie('pass');
        req.session.destroy(function (e) {
            res.status(200).send('ok');
        });
    });


    app.post('/delete', function (req, res) {
        AM.deleteAccount(req.session.user._id, function (e, obj) {
            if (!e) {
                res.clearCookie('user');
                res.clearCookie('pass');
                req.session.destroy(function (e) {
                    res.status(200).send('ok');
                });
            } else {
                res.status(400).send('record not found');
            }
        });
    });

    // add & update excels
    app.get('/excel', function (req, res) {
        var data = {};

        data.title = 'Excel Panel';
        data.udata = req.session.user;

        var callback = function (e, record) {
            var excel, excels = [];
            if (record.length != 0) {
                for (var i in record) {
                    excel = record[i].excel.replace(/\[(.*)\]/, function (match, key) {
                        return key;
                    });
                    if (excel) {
                        excels.push(excel);
                    }
                }
                data.excel = "[" + excels.join(",") + "]";
            }
            res.render('excel', data);
        };

        if (req.session.user.user == "admin") {
            EXM.getAllRecords(callback);
        } else {
            var a = [{user: req.session.user.user}, {user: "admin"}];
            EXM.getUserRecords(a, callback);
        }

    });

    app.post('/excel', function (req, res) {
        EXM.updateExcel({
            user: req.session.user.user,
            excel: req.body['excel']
        }, function (e, o) {
            if (e) {
                res.status(400).send('error-updating-excel');
            } else {
                res.status(200).send('ok');
            }
        });
    });

    app.get('/reservation', function (req, res) {
        // , req.session.user
        console.log('reservation  ');
        var roomId = req.query.roomId;
        console.log("reservation: " + roomId);

        res.render('reservation', {
            title: 'Reservation Panel',
            udata: req.session.user,
            room_id: roomId
        });
    });

    app.get('/reservation-show', function (req, res) {
        console.log('reservation-show');
        var id = req.query.id;
        // var roomId = req.query.roomId;

        res.render('showReservation');
    });


    //获取天气
    app.get('/weathers-get', function (req, res) {
        console.log('weathers-get');
        WRM.getWeather(function (result) { // result 是结果列表
            if (result['id' == 0]) { //if e不为空， 表示出错
                res.status(400).send('error-getting-reservation');
            } else { //成功
                // console.log("result: ", result);
                res.status(200).send(result.data);
            }
        });
    });


    //获取天气
    app.post('/weathers-store', function (req, res) {
        console.log('weathers-store');
        var weatherList = req.body['weatherList'];
        console.log("weatherList : " + weatherList);

        WRM.updateWeathers(weatherList, function (e, result) { // result 是结果列表
            if (e) { //if e不为空， 表示出错
                res.status(400).send('error-getting-reservation');
            } else { //成功
                console.log("result: ", result);
                res.status(200).send(result);
            }
        });
    });


    app.get('/reservation-query', function (req, res) {
        console.log('reservation - query');
        var id = req.query.id;
        REM.getOneReservation({"id": id}, function (result) { // result 是结果列表
            res.status(200).send(result);
        });
    });

    app.post('/findRoomReservation', function (req, res) {

        var roomId = req.body['room_id']; //
        var start = moment(new Date(req.body['start']));
        var end = moment(new Date(req.body['end']));

        var user = req.session.user.user;
        var hashUser = crypto.createHash('md5').update(user).digest('hex');

        var findQuery = {'hash_user': hashUser, 'room_id': roomId, 'start': start.unix(), 'end': end.unix()};

        REM.findRoomReservation(findQuery, function (result) {
            if (result) {
                res.status(200).send(result);
            }

        });
    });


    ///url: /reservation-get?room_id=1&start=1485734400&end=1489363200
    app.get('/reservation-get', function (req, res) {
        console.log('reservation ---- get');
        //获取room_id
        var roomId = req.query.roomId;
        console.log("roomId:" + roomId);
        var query = {"room_id": roomId};
        REM.getAllReservations(query, function (e, result) { // o是结果列表
            if (e) { //if e不为空， 表示出错
                res.status(400).send('error-getting-reservation');
            } else { //成功
                // console.log("result: ", result);
                res.status(200).send(
                    {
                        code: 0,
                        data: result
                    });
            }
        });
    });


    var status = [
        {id: 1, msg: '申请中', btnStatus: 'loading', color: '#F2AE43'},
        {id: 2, msg: '申请成功', btnStatus: 'success', color: '#58B957'},
        {id: 3, msg: '申请失败', btnStatus: 'failed', color: '#DB524B'},
        {id: 4, msg: '已结束', btnStatus: 'finished', color: '#2F79B9'}
    ];

    function myToTidy(data, items) {

        items = items || ['id', 'room_id', 'title', 'start', 'end', 'status', 'date'];
        var tidy = [];

        var now = moment(Date());

        data.forEach(function (element, index) {
            tidy[index] = {};
            items.forEach(function (item) {
                tidy[index][item] = element[item];

                if (item == 'status') {
                    var end = moment.unix(element['end']);

                    //使每个预约以不同的颜色显示， 1， 2， 3 , 4
                    if (now > end) {
                        tidy[index]['color'] = status[3].color;
                        tidy[index]['msg'] = status[3].msg;
                        tidy[index]['status'] = status[3].btnStatus;
                    } else {
                        tidy[index]['color'] = status[Number(element[item]) - 1].color;
                        tidy[index]['msg'] = status[Number(element[item]) - 1].msg;
                        tidy[index]['status'] = status[Number(element[item]) - 1].btnStatus;
                    }
                }
                moment.locale("zh-cn");
                if (item == 'start') {
                    var start = moment.unix(tidy[index]['start']);
                    tidy[index]['start'] = start.format("LLL");
                }

                if (item == 'end') {
                    var end = moment.unix(tidy[index]['end']);
                    tidy[index]['end'] = end.format("LLL");
                }

                if (item == 'date') {
                    tidy[index]['startEnd'] = tidy[index]['start'] + " - " + tidy[index]['end'];
                }
            })
        });
        return tidy;
    }

    //返回我的预约列表页面
    app.get('/reservation-my', function (req, res) {
        console.log('reservation-my');
        var user = req.query.user;

        var query = {"user": user};
        REM.getAllReservations(query, function (e, result) { // o是结果列表
            if (e) { //if e不为空， 表示出错
                res.status(400).send('error-getting-reservation');
            } else { //成功
                var list = myToTidy(result);
                res.render('myReservation', {
                    user: user,
                    list: list
                });
            }
        });
    });


    //返回预约管理列表页面
    app.get('/reservation-manage', function (req, res) {
        console.log('reservation-manage');
        var user = req.query.user;
        // 验证用户是否是管理员

        REM.getAllReservations({}, function (e, result) { // o是结果列表
            if (e) { //if e不为空， 表示出错
                res.status(400).send('error-getting-reservation');
            } else { //成功
                var list = myToTidy(result);
                res.render('manageReservation', {
                    user: user,
                    list: list
                });
            }
        });
    });


    //用户角色检查
    app.post('/account-check', function (req, res) {
        console.log('account-check');
        var user = req.body['user'];

        AM.checkUserRole(user, function (result) {
            res.status(200).send(result);
        });

    });

    //更新预约状态 ， 1 - 申请中 2 - 申请从成功 3 - 申请失败  4 - 已完成
    app.post('/reservation-update-status', function (req, res) {
        console.log('reservation-update-status');

        var id = req.body['id'];
        var user = req.body['user'];
        var status = req.body['status'];

        var retrunValue = {};
        //检查用户是否为管理员
        AM.checkUserRole(user, function (result) {
            if (result.id == 1) { //检查成功， 更新状态
                REM.updateReservationStatus({'id': id, 'status': Number(status)}, function (result) {
                    if (result.id == 1) {
                        retrunValue['id'] = 1;
                        retrunValue['msg'] = '修改成功';
                    } else {
                        retrunValue['id'] = 2;
                        retrunValue['msg'] = '修改失败';
                    }
                    //返回结果
                    res.status(200).send(retrunValue);
                });
            } else { //检查失败
                retrunValue['id'] = 2;
                retrunValue['msg'] = '您没有修改权限';
                //返回结果
                res.status(200).send(retrunValue);
            }

        });
    });


    //返回申请预约页面
    app.get('/reservation-add', function (req, res) {
        console.log('get reservation-add');
        var roomId = req.query.roomId;
        console.log("roomId ---- : " + roomId);
        res.render('addReservation', {
            title: roomId
        });
    });

    //添加预约申请
    app.post('/reservation-add', function (req, res) {
        console.log('post reservation-add');

        var title = req.body['title']; //公司/团队名称
        var incName = req.body['inc_name']; //公司/团队名称
        var leaderName = req.body['leader_name']; //负责人姓名
        var roomName = req.body['room_name'];
        var leaderMobile = req.body['leader_mobile'];
        var incTel = req.body['inc_tel'];
        var incEmail = req.body['inc_email'];

        var startTime = req.body['start'];
        var endTime = req.body['end'];
        var allDay = req.body['allDay'];

        var postName = req.body['post_name'];
        var recruitProfessional = req.body['recruit_professional'];
        var enrolmentNumbers = req.body['enrolment_numbers'];
        var workingPlace = req.body['working_place'];
        var jobRequirements = req.body['job_requirements'];
        var workingConditions = req.body['working_conditions'];

        var theIntern = req.body['the_intern'];
        var detailInfo = req.body['detail_info'];

        var id = req.body['id'];
        var roomId = req.body['room_id'];

        //标记状态为申请中
        var status = 1;

        //申请时间
        // var date = moment().format('MMMM Do YYYY, h:mm:ss a');
        var date = moment();

        var user = req.session.user.user;
        //user hash
        var hashUser = crypto.createHash('md5').update(user).digest('hex');


        var start = moment(new Date(startTime));
        var end = moment(new Date(endTime));

        if (Number(allDay) == 1) {
            allDay = true;
        } else {
            allDay = false;
        }

        //保存到数据库中
        REM.updateReservation({

            user: user,
            hash_user: hashUser,

            id: id,
            room_id: roomId,

            title: title,

            inc_name: incName,
            leader_name: leaderName,
            room_name: roomName,
            leader_mobile: leaderMobile,
            inc_tel: incTel,
            inc_email: incEmail,

            start: start.unix(),
            end: end.unix(),
            allDay: allDay,

            post_name: postName,
            recruit_professional: recruitProfessional,
            enrolment_numbers: enrolmentNumbers,
            working_place: workingPlace,
            job_requirements: jobRequirements,
            working_conditions: workingConditions,
            the_intern: theIntern,
            detail_info: detailInfo,

            status: status,
            date: date.toISOString()

        }, function (result) {
            console.log('result : ' + result);
            res.status(200).send(result);
        });
    });


    app.post('/reservation-remove', function (req, res) {
        console.log('reservation-remove');

        var data = {};
        data['id'] = req.body['id'] ? Number(req.body['id']) : null;
        data['user'] = req.body['user'];

        AM.checkUserRole(data['user'], function (result) {

            if (result.id == 1) { //用户为管理员
                data['userType'] = 1;
            } else { //普通用户
                data['userType'] = 2;
            }
            console.log('data --- ' + data);

            REM.removeReservation(data, function (values) {
                console.log('remove values ' + values);
                res.status(200).send(values);
            });
        });
    });


    app.get('/information', function (req, res) {
        res.render('information', {
            title: 'information Panel',
            udata: req.session.user
        });
    });

    app.get('/information-get', function (req, res) {
        var callback = function (e, record) {
            var infos = [], result;

            if (record && record.length != 0) {
                for (var i in record) {
                    infos.push(JSON.parse(record[i].taskItem));
                }
            }
            result = infos.length === 0 ? undefined : JSON.stringify(infos);
            if (e) {
                res.status(400).send('error-getting-information');
            } else {
                res.status(200).send(result);
            }
        };

        if (req.session.user.user == "admin") {
            IFM.getAllRecords(callback);
        } else {
            IFM.getInformation({
                user: req.session.user.user,
            }, callback);
        }
    });

    app.post('/information-add', function (req, res) {
        IFM.addInformation({
            user: req.session.user.user,
            taskItem: req.body['taskItem'],
            content: req.body['content']
        }, function (e, o) {
            if (e) {
                res.status(400).send('error-adding-reservation');
            } else {
                res.status(200).send('ok');
            }
        });
    });
    app.post('/information-delete', function (req, res) {
        var indexes = req.body['indexes'];
        var num = 0, len = indexes.length;
        var callback = function (e, o) {
            num++;
            if (num === len) {
                if (e) {
                    res.status(400).send('error-deleting-reservation');
                } else {
                    res.status(200).send('ok');
                }
            }
        };
        for (var i in indexes) {
            if (req.session.user.user == "admin") {
                IFM.deleteInformation({
                    index: indexes[i]
                }, callback)
            } else {
                IFM.deleteInformation({
                    user: req.session.user.user,
                    index: indexes[i]
                }, callback)
            }
        }
    });
    app.post('/information-publish', function (req, res) {
        var indexes = req.body['indexes'];
        var num = 0, len = indexes.length;
        var callback = function (e, o) {
            num++;
            if (num === len) {
                if (e) {
                    res.status(400).send('error-deleting-reservation');
                } else {
                    res.status(200).send('ok');
                }
            }
        };
        for (var i in indexes) {
            if (req.session.user.user == "admin") {
                IFM.publishInformation({
                    index: indexes[i]
                }, callback)
            }
        }
    });

    app.get('/Information-filter', function (req, res) {
        var callback = function (e, record) {
            if (e) {
                res.status(400).send('error-getting-information');
            } else {
                res.status(200).send(record);
            }
        };
        IFM.filterInformation(callback);
    });


    app.post('/file-get', function (req, res) {
        FIM.getFile({index: req.body['index']}, function (e, o) {
            if (e) {
                res.status(400).send('error-getting-reservation');
            } else {
                res.status(200).send(o);
            }
        });
    });


    //Guard Normal User
    app.all('*', function (req, res, next) {
        if (req.session.user && req.session.user.user == "admin") {
            next();
        } else {
            res.render('404', {title: 'Page Not Found'});
        }
    });


    app.get('/printAccount', function (req, res) {
        AM.getAllRecords(function (e, accounts) {
            res.render('print', {title: 'Account List', accts: accounts});
        })
    });

    app.get('/resetAccount', function (req, res) {
        AM.delAllRecords(function () {
            res.redirect('/print');
        });
    });

    app.get('/printExcel', function (req, res) {
        EXM.getAllRecords(function (e, excels) {
            res.render('printExcel', {title: 'Excel List', exls: excels});
        });
    });

    app.get('/resetExcel', function (req, res) {
        EXM.delAllRecords(function () {
            res.redirect('/printExcel');
        });
    });

    app.get('/printReservation', function (req, res) {
        REM.getAllReservations(function (e, reservations) {
            res.render('printReservation', {title: 'Reservations List', resns: reservations});
        });
    });

    app.get('/resetReservation', function (req, res) {
        REM.delAllRecords(function () {
            res.redirect('/printReservation');
        });
    });

    app.get('/printInformation', function (req, res) {
        IFM.getAllRecords(function (e, informations) {
            res.render('printInformation', {title: 'Informations List', infos: informations});
        });
    });

    app.get('/resetInformation', function (req, res) {
        IFM.delAllRecords(function () {
            res.redirect('/printInformation');
        });
    });

    app.get('/printFile', function (req, res) {
        FIM.getAllRecords(function (e, files) {
            res.render('printFile', {title: 'files List', files: files});
        });
    });

    app.get('/resetFile', function (req, res) {
        FIM.delAllRecords(function () {
            res.redirect('/printFile');
        });
    });

    app.all('*', function (req, res) {
        res.render('404', {title: 'Page Not Found'});
    });

}